/**
 * @name         RepNET View Generator for reporting engine
 * @version      1.0a
 * @author       Kasun Rathnayaka <kazar55@gmail.com>
 * @author       Ramindu Deshapriya <rasade88@gmail.com>
 * @author               Prabodha Dissanayake <prabodha89@gmail.com>
 * @author               Thusira Dissanayake <thusira14@gmail.com>
 * @about        Developed by MiDi
 * @license      http://www.gnu.org/licenses/lgpl-2.1.html GNU Lesser General Public License (LGPL)
 * @lastModified 2012.09.24
 */
package com.midi.repnet.ui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Vector;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.JButton;

import com.midi.repnet.main.PasswordChecker;
import com.midi.repnet.main.Printer;
//import com.midi.repnet.main.Printer;
import com.midi.repnet.main.Reports;
import com.midi.repnet.models.*;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

import li.netcat.print.util.PagePrint;

public class ViewGenerator extends JFrame {
	public static final int REPORT_TYPE_CREDIT_OVERDUE = 1;
	public static final int REPORT_TYPE_CHEQUE_RESULTS = 2;
	public static final int REPORT_TYPE_CREDIT_COLLECTION = 3;
	public static final int REPORT_TYPE_WHOLESALE = 4;
	public static final int REPORT_TYPE_CREDIT_PAID = 5;
	private JPanel contentPane;
	public static JFrame final_frame;
	private String cheque_date;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					final_frame = new ViewGenerator();
					final_frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	public ViewGenerator() {
		super();
	}

	/**
	 * Method to create the frame
	 * 
	 * @param params
	 *            a HashMap containing params needing to be processed when
	 *            generating each view
	 * @param reportType
	 *            One of the contants on report creation
	 * @wbp.parser.constructor
	 */
	public ViewGenerator(HashMap<String, Object> params, int reportType) {
		switch (reportType) {
		case REPORT_TYPE_CREDIT_OVERDUE:
			setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
			setBounds(100, 100, 450, 381);
			contentPane = new JPanel();
			contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
			setContentPane(contentPane);
			ArrayList<CreditElement> list = Reports.getOverdueCredit(params
					.get("date").toString());
			setUiOverdue(list);
			break;
		case REPORT_TYPE_CHEQUE_RESULTS:
			cheque_date = params.get("date").toString();
			setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
			setBounds(100, 100, 450, 381);
			contentPane = new JPanel();
			contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
			setContentPane(contentPane);
			ArrayList<ChequeResults> results = Reports
					.getChequeListForDate(cheque_date);
			setUiChequeResults(results);
			break;
		case REPORT_TYPE_CREDIT_COLLECTION:
			setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
			setBounds(100, 100, 450, 381);
			contentPane = new JPanel();
			contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
			setContentPane(contentPane);
			ArrayList<CreditElement> creditList = Reports
					.getCreditCollectionList(params);
			setUiCreditCollection(creditList);
			break;
		case REPORT_TYPE_CREDIT_PAID:
			setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
			setBounds(100, 100, 450, 381);
			contentPane = new JPanel();
			contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
			setContentPane(contentPane);
			ArrayList<CreditElement> paidList = Reports
					.getCreditPaidList(params);
			setUiCreditPaid(paidList);
			break;
		}
	}

	private void setUiCreditPaid(ArrayList<CreditElement> paidList) {
		final String col[] = { "Date", "Bill No", "Shop", "Region", "Agency",
				"Total" };
		final ArrayList<CreditElement> list = paidList;
		try {
			// Printer rpt = new
			// Printer(col,results,REPORT_TYPE_CREDIT_COLLECTION);
			// rpt.setVisible(true);
			// rpt.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		} catch (Exception e) {
			e.printStackTrace();
		}
		final DefaultTableModel model = new DefaultTableModel(null, col) {
			public boolean isCellEditable(int row, int column) {
				return false;// This causes all cells to be not editable
			}
		};

		for (CreditElement l : paidList) // Adding the respective cheques to the
											// table
		{
			model.addRow(new String[] { l.getDate(), l.getBill_no(),
					l.getShop(), l.getRegion(), l.getAgency(),
					l.getAmount() });
		}

		final JTable table = new JTable(model);
		JTableHeader header = table.getTableHeader();
		table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
		header.setBackground(Color.yellow);
		contentPane.setLayout(null);
		JScrollPane pane = new JScrollPane(table);
		pane.setBounds(5, 5, 700, 281);

		contentPane.add(pane);
		this.setSize(715, 350);
		this.setTitle("Credit Paid List");
	}

	private void setUiCreditCollection(ArrayList<CreditElement> results) {
		final String col[] = { "Date", "Bill No", "Shop", "Region", "Agency",
				"Total", "Remaining" };
		final ArrayList<CreditElement> list = results;
		final DefaultTableModel model = new DefaultTableModel(null, col) {
			public boolean isCellEditable(int row, int column) {
				if (column == 5) {
					return true;
				} else
					return false;// This causes all cells to be not editable
			}
		};

		for (CreditElement l : results) // Adding the respective cheques to the
										// table
		{
			model.addRow(new String[] { l.getDate(), l.getBill_no(),
					l.getShop(), l.getRegion(), l.getAgency(),
					l.getAmount(),
					l.getRemainder() });
		}

		final JTable table = new JTable(model);
		table.setName("CreditCollection");
		JTableHeader header = table.getTableHeader();
		table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
		header.setBackground(Color.yellow);
		contentPane.setLayout(null);
		JScrollPane pane = new JScrollPane(table);
		pane.setBounds(5, 5, 700, 281);

		contentPane.add(pane);
		JButton btnPrint = new JButton("Print");
		btnPrint.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {

				// add password to print button

				int id = 2;
				boolean check = PasswordChecker.checkResult(id);
				// Uses boolean to determine if password is valid
				if (check == true) {
					// HeaderFooterExample.set(col,
					// list,REPORT_TYPE_CREDIT_COLLECTION);
					Printer rpt;
					try {
						// rpt = new Printer(list,
						// col,REPORT_TYPE_CREDIT_COLLECTION);
						
						Vector data = model.getDataVector();
						
						
						final DefaultTableModel new_model = new DefaultTableModel(null, col) {
							public boolean isCellEditable(int row, int column) {
								if (column == 5) {
									return true;
								} else
									return false;// This causes all cells to be not editable
							}
						};
//						Vector row = (Vector)data.elementAt(1);
//						row = (Vector)row.clone();
//						new_model.addRow(row);
//						JTable new_table = new JTable(new_model);
//						
//						rpt = new Printer(table);
//						rpt.setVisible(true);
//						rpt.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
						
					} catch (Exception e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}

				} else {
					JOptionPane.showMessageDialog(null,
							"Enter Correct Password");

				}

			}
		});

		btnPrint.setBounds(89, 297, 89, 23);
		contentPane.add(btnPrint);

		JButton btnRemove = new JButton("Remove Entry");
		btnRemove.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int selectedRow = table.getSelectedRow();
				if (selectedRow < 0) {
					JOptionPane.showMessageDialog(null,
							"Please select an Entry");
				} else {
					model.removeRow(selectedRow);
				}

			}
		});

		btnRemove.setBounds(200, 297, 150, 23);
		contentPane.add(btnRemove);
		this.setSize(715, 350);
		this.setTitle("Credit Collection List");

	}

	// /////////////////////////////////////////////////////////////////////////////////////////////////
	// set UI ChequeResutl

	public void setUiChequeResults(final ArrayList<ChequeResults> list) {

		final String col[] = { "Date", "Bill Number", "Shop", "Cheque No",
				"Bank", "Amount", "Status" };
		final DefaultTableModel model = new DefaultTableModel(null, col) {
			public boolean isCellEditable(int row, int column) {
				return false;// This causes all cells to be not editable
			}
		};

		for (ChequeResults l : list) // Adding the respective cheques to the
										// table
		{
			model.addRow(new String[] { l.getDate(), l.getBill_no(),
					l.getShop(), l.getCheque_no(), l.getBank(),
					Float.toString(l.getAmount()), l.getStatus() });
		}

		final JTable table = new JTable(model);

		JTableHeader header = table.getTableHeader();
		header.setBackground(Color.yellow);
		contentPane.setLayout(null);
		JScrollPane pane = new JScrollPane(table);
		pane.setBounds(5, 5, 432, 281);
		contentPane.add(pane);
		JButton btnChequeBounced = new JButton("Cheque Bounced");
		btnChequeBounced.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) { // Button action
				int selectedRowIndex = table.getSelectedRow();
				int selectedColumnIndex = table.getSelectedColumn();
				String selectedBillNo = (String) table.getModel().getValueAt(
						selectedRowIndex, 1); // getting the selected row and
												// 2nd column to get bill no
				float amount = Float.parseFloat(table.getModel()
						.getValueAt(selectedRowIndex, 5).toString());
				String cheque_no = table.getModel()
						.getValueAt(selectedRowIndex, 3).toString();

				if (table.getModel().getValueAt(selectedRowIndex, 6).toString().equalsIgnoreCase("ok")) {
					Reports.updateChequeBounce(selectedBillNo, amount,
							cheque_no);
					table.getModel().setValueAt("Bounced", selectedRowIndex, 6);
				} else {
					JOptionPane.showMessageDialog(null,
							"Cheque already Bounced..");
				}

			}
		});
		btnChequeBounced.setBounds(178, 297, 131, 23);
		contentPane.add(btnChequeBounced);

		JButton btnNewButton = new JButton("Delete Cheque");
		btnNewButton.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent arg0) { // Cheque Delete
															// Button

				int selectedRow = table.getSelectedRow();
				String cheque_no = (String) table.getModel().getValueAt(
						selectedRow, 3);
				float amount = Float.parseFloat(table.getModel()
						.getValueAt(selectedRow, 5).toString());
				String bill_no = (String) table.getModel().getValueAt(
						selectedRow, 1);
				model.removeRow(selectedRow);

				// System.out.println(amount);

				Reports.deleteCheque(cheque_no, bill_no, amount); // pass
																	// cheque_no
																	// to
																	// Reports.java

			}
		});
		btnNewButton.setBounds(308, 297, 124, 23);
		contentPane.add(btnNewButton);

		JButton btnPrint = new JButton("Print");
		btnPrint.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {

				// add password to print button

				int id = 2;
				boolean check = PasswordChecker.checkResult(id);
				// Uses boolean to determine if password is valid
				if (check == true) {

					JTable new_table = new JTable(model);
					Printer rpt;
					try {
						rpt = new Printer(Reports
								.getChequeListForDate(cheque_date), col,
								REPORT_TYPE_CHEQUE_RESULTS,null);
						rpt.setVisible(true);
						rpt.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
					} catch (Exception e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}

					// new
					// PrintPreview(SimpleTableExample.createPrint(col,list)).open();
					// new PrintPreview(new
					// PagePrint(SimpleTableExample.createPrint(col,list),
					// createPageDecorator())).open();

					// Printer.printMethod(model);
				} else {
					JOptionPane.showMessageDialog(null,
							"Enter Correct Password");

				}

			}
		});

		btnPrint.setBounds(89, 297, 89, 23);
		contentPane.add(btnPrint);
	}

	// //////////////////////////////////////////////////////////////////////////////////////////////
	// Set UI Credit overdue

	public void setUiOverdue(ArrayList<CreditElement> list) {

		String col[] = { "Date", "Bill No", "Shop", "Agency", "Amount" };
		final DefaultTableModel model = new DefaultTableModel(null, col) {
			public boolean isCellEditable(int row, int column) {
				return false;// This causes all cells to be not editable
			}
		};

		for (CreditElement l : list) // Adding the respective cheques to the
										// table
		{
			model.addRow(new String[] { l.getDate(), l.getBill_no(),
					l.getShop(), l.getAgency(), l.getAmount() });
		}

		final JTable table = new JTable(model);
		JTableHeader header = table.getTableHeader();
		DefaultTableCellRenderer rightRenderer = new DefaultTableCellRenderer();
		rightRenderer.setHorizontalAlignment( JLabel.RIGHT );
		table.getColumnModel().getColumn(4).setCellRenderer( rightRenderer );
		header.setBackground(Color.yellow);
		contentPane.setLayout(null);
		JScrollPane pane = new JScrollPane(table);
		pane.setBounds(5, 5, 432, 281);
		contentPane.add(pane);

	}
}